import { createRouter,createWebHistory } from "vue-router";
import store from '@/store';
import userRoutes from './module/user';
import articleRoutes from "./module/article";

let router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            name: 'Home',
            component: () => import('@/views/Home.vue'),
            meta: {
                title: "我与春风结过客"
            }
        },
        {
            path: '/tool',
            name: 'Tool',
            component: () => import('@/views/Tool.vue'),
            meta: {
                title: "快捷工具"
            }
            
        },
        ...userRoutes,
        ...articleRoutes,
        {
            path: '/404',
            name: '404',
            component: () => import('@/views/404.vue'),
            meta: {
                title: "404"
            }
        },
        {
            path: '/:pathMatch(.*)',
            redirect: '/404'
        }
    ]
})

router.beforeEach((to, from, next) => {
    if (to.meta.auth) { // 判断是否需要登录
        // 判断用户是否登录
        if (store.state.userModule.token) {
        // 如果token无效，需要请求token
        next();
        } else {
        // 跳转登录
        router.push({ name: 'Login' });
        }
    } else {
        next();
    }
});

export default router;